#include "../lvgl/lvgl.h"
#include "iu_manage.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

// 全局变量
static lv_obj_t * ticket_screen        = NULL;
static lv_obj_t * content_area         = NULL;
static lv_obj_t * movie_selection_page = NULL;
static lv_obj_t * time_selection_page  = NULL;
static lv_obj_t * seat_selection_page  = NULL;
static Movie current_movie;
static int current_movie_index                = 0;
static char selected_date[20]                 = "";
static char selected_time[20]                 = "";
static char selected_hall[5]                  = "";
static int selected_seats[MAX_SELECTED_SEATS] = {0};
static int selected_count                     = 0;
static PageType current_page_type             = PAGE_MOVIE_SELECTION;
static lv_obj_t * prev_selected_time_btn      = NULL;
static lv_obj_t * prev_date_btn               = NULL;
static Movie * movies                         = NULL;
static int movie_count                        = 0;
static ShowTime * show_times                  = NULL;
static int show_time_count                    = 0;
static DateInfo date_options[3];
static SeatStatus seats[SEAT_ROWS][SEAT_COLS];

// 外部变量声明
extern lv_obj_t * menu_screen;
extern bool menu_screen_hidden;
extern lv_timer_t * time_timer;

// 函数声明部分，删除重复声明
extern void create_main_menu(void);

// 函数声明
static void msgbox_event_handler(lv_event_t * e);
static void back_btn_handler(lv_event_t * e);
static lv_obj_t * create_back_button(lv_obj_t * parent);
static void clear_content_area(void);
static void confirm_purchase(lv_event_t * e);
static void seat_click_handler(lv_event_t * e);
static void time_select_handler(lv_event_t * e);
static void date_select_handler(lv_event_t * e);
static void movie_select_handler(lv_event_t * e);
static void show_movie_selection_page(void);
static void show_time_selection_page(void);
static void show_seat_selection_page(void);
static char * generate_ticket_number(int seat_idx);
static bool save_purchase_info(void);
static void close_msgbox_timer_cb(lv_timer_t * timer);
static bool load_movies_from_file(void);
static bool load_show_times_from_file(void);
static void free_movies(void);
static void free_show_times(void);
static void init_date_options(void);
static void reset_seat_selection(void);
static void update_seat_status_from_file(void);
static void update_show_time_remaining(void);
static void set_btn_transition(lv_obj_t * btn);
static bool is_date_exists_in_file(const char * date);
static void generate_show_times(void);
static void init_show_times_for_dates(void);
void buy_tickets_screen_init_new(void); // 添加函数原型声明
static void close_msgbox_simple_cb(lv_timer_t * timer);
static void stop_all_timers(void);
static void switch_to_pickup_screen_timer_cb(lv_timer_t * timer);
static void add_showtime_buttons(lv_obj_t * parent);
static void update_seat_display(lv_obj_t * seat_container);
static void create_seats(lv_obj_t * parent);

// 初始化日期选项（今天、明天、后天）
static void init_date_options(void)
{
    time_t now;
    struct tm tm_info;
    time(&now);
    tm_info = *localtime(&now);

    for(int i = 0; i < 3; i++) {
        // 创建当前日期的副本用于计算
        struct tm current_tm = tm_info;
        // 增加天数
        current_tm.tm_mday += i;
        // 规范化日期（处理月份/年份变更）
        mktime(&current_tm);

        date_options[i].year  = current_tm.tm_year + 1900;
        date_options[i].month = current_tm.tm_mon + 1;
        date_options[i].day   = current_tm.tm_mday;

        // 格式化显示字符串为实际日期，如"2023-06-15" (统一使用连字符格式)
        snprintf(date_options[i].display, sizeof(date_options[i].display), "%d-%02d-%02d", date_options[i].year,
                 date_options[i].month, date_options[i].day);
    }
}

// 设置按钮过渡动画
static void set_btn_transition(lv_obj_t * btn)
{
    lv_style_transition_dsc_t * tr = lv_mem_alloc(sizeof(lv_style_transition_dsc_t));
    lv_style_prop_t * props        = lv_mem_alloc(3 * sizeof(lv_style_prop_t));
    props[0]                       = LV_STYLE_BG_COLOR;
    props[1]                       = LV_STYLE_RADIUS;
    props[2]                       = 0;
    lv_style_transition_dsc_init(tr, props, lv_anim_path_linear, 200, 0, NULL);
    lv_obj_set_style_transition(btn, tr, 0);
}

// 从movie.txt文件加载电影信息
static bool load_movies_from_file(void)
{
    free_movies();

    FILE * file = fopen("movie.txt", "r");
    if(!file) {
        LV_LOG_USER("Failed to open movie.txt for reading");
        return false;
    }

    // 读取文件内容到缓冲区
    char * buffer = NULL;
    fseek(file, 0, SEEK_END);
    long filesize = ftell(file);
    fseek(file, 0, SEEK_SET);

    // 分配缓冲区内存
    buffer = (char *)malloc(filesize + 1);
    if(!buffer) {
        LV_LOG_USER("Failed to allocate memory for file buffer");
        fclose(file);
        return false;
    }

    // 读取文件内容
    size_t bytes_read = fread(buffer, 1, filesize, file);
    if(bytes_read != (size_t)filesize) {
        LV_LOG_USER("Failed to read movie.txt");
        free(buffer);
        fclose(file);
        return false;
    }

    buffer[filesize] = '\0'; // 确保字符串结尾

    // 计算行数
    int count         = 0;
    char * line_start = buffer;
    for(long i = 0; i < filesize; i++) {
        if(buffer[i] == '\n') {
            count++;
            if(i + 1 < filesize && buffer[i + 1] == '\r') i++; // 跳过\r
        }
    }
    if(filesize > 0 && buffer[filesize - 1] != '\n') count++; // 如果最后一行没有换行符

    if(count == 0) {
        LV_LOG_USER("No valid lines found in movie.txt");
        free(buffer);
        fclose(file);
        return false;
    }

    LV_LOG_USER("Found %d lines in movie.txt", count);

    // 为电影数据分配内存
    movies = malloc(count * sizeof(Movie));
    if(!movies) {
        LV_LOG_USER("Failed to allocate memory for movies");
        free(buffer);
        fclose(file);
        return false;
    }

    // 初始化电影数据
    movie_count = 0;
    char movie_name[100];
    char duration[20];
    int price;
    int movie_id;

    // 解析缓冲区内容 - 格式: 编号,电影名,时长,单价
    line_start      = buffer;
    char * line_end = strchr(line_start, '\n');
    while(line_start && *line_start) {
        if(line_end) *line_end = '\0'; // 临时替换换行符为字符串结束符

        // 移除行尾的换行符和回车符
        char * cr = strchr(line_start, '\r');
        if(cr) *cr = '\0';

        LV_LOG_USER("Parsing line: %s", line_start);

        // 使用更灵活的解析方式
        char * token = strtok(line_start, ",");
        if(!token) {
            if(line_end) *line_end = '\n'; // 恢复换行符
            line_start = (line_end) ? line_end + 1 : NULL;
            if(line_start && *line_start == '\r') line_start++;
            line_end = strchr(line_start, '\n');
            continue;
        }
        movie_id = atoi(token);

        token = strtok(NULL, ",");
        if(!token) {
            if(line_end) *line_end = '\n';
            line_start = (line_end) ? line_end + 1 : NULL;
            if(line_start && *line_start == '\r') line_start++;
            line_end = strchr(line_start, '\n');
            continue;
        }
        strncpy(movie_name, token, sizeof(movie_name) - 1);
        movie_name[sizeof(movie_name) - 1] = '\0';

        token = strtok(NULL, ",");
        if(!token) {
            if(line_end) *line_end = '\n';
            line_start = (line_end) ? line_end + 1 : NULL;
            if(line_start && *line_start == '\r') line_start++;
            line_end = strchr(line_start, '\n');
            continue;
        }
        strncpy(duration, token, sizeof(duration) - 1);
        duration[sizeof(duration) - 1] = '\0';

        token = strtok(NULL, ",");
        if(!token) {
            if(line_end) *line_end = '\n';
            line_start = (line_end) ? line_end + 1 : NULL;
            if(line_start && *line_start == '\r') line_start++;
            line_end = strchr(line_start, '\n');
            continue;
        }
        price = atoi(token);

        LV_LOG_USER("Parsed movie: id=%d, name=%s, duration=%s, price=%d", movie_id, movie_name, duration, price);

        // 复制电影信息
        movies[movie_count].id       = movie_id;
        movies[movie_count].name     = strdup(movie_name);
        movies[movie_count].duration = strdup(duration);
        movies[movie_count].price    = price;
        movies[movie_count].hall     = NULL; // 影厅信息现在从time.txt获取

        // 初始化times数组和remaining数组
        for(int j = 0; j < 10; j++) {
            movies[movie_count].times[j]     = NULL;
            movies[movie_count].remaining[j] = 0;
        }

        movie_count++;

        if(line_end) *line_end = '\n'; // 恢复换行符
        line_start = line_end ? line_end + 1 : NULL;
        if(line_start && *line_start == '\r') line_start++;
        line_end = line_start ? strchr(line_start, '\n') : NULL;

        if(movie_count >= count) break;
    }

    free(buffer);
    fclose(file);
    LV_LOG_USER("Successfully loaded %d movies", movie_count);
    return movie_count > 0;
}

//=================================================================================================================

// 检查指定日期是否已存在于time.txt文件中
static bool is_date_exists_in_file(const char * date)
{
    FILE * file = fopen("time.txt", "r");
    if(!file) return false;

    char line[1024]; // 增加缓冲区大小以适应包含座位状态的长行
    char file_date[20];
    int movie_id;
    char hall[5];
    char time[10];
    int total_seats, remaining_seats;

    while(fgets(line, sizeof(line), file)) {
        if(sscanf(line, "%d,%19[^,],%4[^,],%9[^,],%d,%d", &movie_id, file_date, hall, time, &total_seats,
                  &remaining_seats) == 6) {
            if(strcmp(file_date, date) == 0) {
                fclose(file);
                return true;
            }
        }
    }

    fclose(file);
    return false;
}

// 生成场次安排
static void generate_show_times(void)
{
    // 检查time.txt文件是否存在，不存在则创建
    FILE * file = fopen("time.txt", "a+");
    if(!file) {
        LV_LOG_USER("Failed to open or create time.txt");
        return;
    }
    fclose(file);

    // 初始化未来3天的场次安排（包括今天）
    init_show_times_for_dates();
}

// 为指定日期初始化场次安排
static void init_show_times_for_dates(void)
{
    time_t now;
    struct tm * tm_info;
    time(&now);

    // 生成今日及未来两天的日期
    for(int day_offset = 0; day_offset < 3; day_offset++) {
        time_t day_time = now + day_offset * 24 * 60 * 60;
        tm_info         = localtime(&day_time);

        // 格式化日期为 YYYY-MM-DD (统一使用连字符格式)
        char date_str[20];
        strftime(date_str, sizeof(date_str), "%Y-%m-%d", tm_info);

        // 检查该日期是否已存在于文件中
        if(is_date_exists_in_file(date_str)) {
            LV_LOG_USER("Date %s already exists in time.txt, skipping", date_str);
            continue;
        }

        // 加载电影列表以获取电影数量
        if(movie_count == 0) {
            load_movies_from_file();
        }

        if(movie_count == 0) {
            LV_LOG_USER("No movies available for show time generation");
            return;
        }

        // 定义场次时间
        const char * show_times_list[] = {"09:30", "11:30", "14:10", "16:10", "18:10", "20:10", "22:10"};
        const int show_times_count     = 7;

        // 定义影厅
        const char * halls[]  = {"A", "B", "C", "D"};
        const int halls_count = 4;

        // 创建一个临时数组来跟踪哪些电影已被分配
        int * assigned_movies = (int *)calloc(movie_count, sizeof(int));
        int assigned_count    = 0;

        // 为每个影厅安排场次
        for(int hall_idx = 0; hall_idx < halls_count; hall_idx++) {
            // 为每个场次安排电影
            for(int time_idx = 0; time_idx < show_times_count; time_idx++) {
                // 选择电影，确保每部电影至少播放一次
                int movie_id = 0;
                if(assigned_count < movie_count) {
                    // 确保每部电影至少播放一次
                    movie_id                        = movies[assigned_count].id;
                    assigned_movies[assigned_count] = 1;
                    assigned_count++;
                } else {
                    // 其他场次随机选择已分配过的电影
                    int movie_index;
                    do {
                        movie_index = rand() % movie_count;
                    } while(assigned_movies[movie_index] == 0 && assigned_count < movie_count);
                    movie_id = movies[movie_index].id;
                }

                // 准备写入文件的数据
                FILE * file = fopen("time.txt", "a");
                if(file) {
                    // 写入基本信息: 电影编号,日期,影厅,场次,总座位数,剩余座位数
                    fprintf(file, "%d,%s,%s,%s,45,45", movie_id, date_str, halls[hall_idx], show_times_list[time_idx]);

                    // 写入座位状态信息 (45个座位全部初始化为可选状态)
                    for(int i = 0; i < SEAT_ROWS * SEAT_COLS; i++) {
                        fprintf(file, ",0"); // 0 表示 SEAT_AVAILABLE
                    }
                    fprintf(file, "\n");
                    fclose(file);
                }
            }
        }

        free(assigned_movies);
        LV_LOG_USER("Generated show times for date: %s", date_str);
    }
}
// 从time.txt加载场次安排 - 修复日期解析问题
static bool load_show_times_from_file(void)
{
    free_show_times();

    FILE * file = fopen("time.txt", "r");
    if(!file) {
        LV_LOG_USER("Failed to open time.txt for reading: %s", strerror(errno));
        perror("fopen time.txt");
        return false;
    }

    // 计算文件行数
    int count = 0;
    char line[1024]; // 增加缓冲区大小以适应包含座位状态的长行
    while(fgets(line, sizeof(line), file)) {
        count++;
    }

    if(count == 0) {
        LV_LOG_USER("No valid lines found in time.txt");
        fclose(file);
        return false;
    }

    LV_LOG_USER("Found %d lines in time.txt", count);
    rewind(file);

    // 分配内存
    show_times = malloc(count * sizeof(ShowTime));
    if(!show_times) {
        LV_LOG_USER("Failed to allocate memory for show times");
        fclose(file);
        return false;
    }

    // 读取场次信息 - 格式: 电影编号,日期,影厅,场次,总座位数,剩余座位数,座位状态(按行存储)
    show_time_count = 0;
    int movie_id;
    char date[20];
    char hall[5];
    char time[10];
    int total_seats, remaining_seats;

    while(fgets(line, sizeof(line), file) && show_time_count < count) {
        // 移除行尾的换行符
        line[strcspn(line, "\r\n")] = 0;

        // 使用更宽松的解析方式
        char * token = strtok(line, ",");
        if(!token) continue;
        movie_id = atoi(token);

        token = strtok(NULL, ",");
        if(!token) continue;
        strncpy(date, token, sizeof(date) - 1);
        date[sizeof(date) - 1] = '\0';

        token = strtok(NULL, ",");
        if(!token) continue;
        strncpy(hall, token, sizeof(hall) - 1);
        hall[sizeof(hall) - 1] = '\0';

        token = strtok(NULL, ",");
        if(!token) continue;
        strncpy(time, token, sizeof(time) - 1);
        time[sizeof(time) - 1] = '\0';

        token = strtok(NULL, ",");
        if(!token) continue;
        total_seats = atoi(token);

        token = strtok(NULL, ",");
        if(!token) continue;
        remaining_seats = atoi(token);

        LV_LOG_USER("Parsed showtime: movie_id=%d, date=%s, hall=%s, time=%s, total=%d, remaining=%d", movie_id, date,
                    hall, time, total_seats, remaining_seats);

        show_times[show_time_count].movie_id = movie_id;
        strcpy(show_times[show_time_count].date, date);
        strcpy(show_times[show_time_count].hall, hall);
        strcpy(show_times[show_time_count].time, time);
        show_times[show_time_count].total_seats     = total_seats;
        show_times[show_time_count].remaining_seats = remaining_seats;

        // 初始化座位状态
        for(int i = 0; i < SEAT_ROWS; i++) {
            for(int j = 0; j < SEAT_COLS; j++) {
                show_times[show_time_count].seat_status[i][j] = SEAT_AVAILABLE;
            }
        }

        // 读取座位状态信息
        for(int i = 0; i < SEAT_ROWS; i++) {
            for(int j = 0; j < SEAT_COLS; j++) {
                token = strtok(NULL, ",");
                if(token) {
                    int status = atoi(token);
                    if(status >= SEAT_AVAILABLE && status <= SEAT_RESERVED) {
                        show_times[show_time_count].seat_status[i][j] = (SeatStatus)status;
                    }
                }
            }
        }

        show_time_count++;
    }

    fclose(file);
    LV_LOG_USER("Successfully loaded %d show times", show_time_count);
    return show_time_count > 0;
}
//==================================================================================================================

// 释放电影数据内存
static void free_movies(void)
{
    if(movies) {
        for(int i = 0; i < movie_count; i++) {
            if(movies[i].name) {
                free(movies[i].name);
                movies[i].name = NULL;
            }
            if(movies[i].duration) {
                free(movies[i].duration);
                movies[i].duration = NULL;
            }
            // 注意：hall字段现在从time.txt获取，可能为NULL
            if(movies[i].hall) {
                free(movies[i].hall);
                movies[i].hall = NULL;
            }
            for(int j = 0; j < 10; j++) {
                if(movies[i].times[j]) {
                    free(movies[i].times[j]);
                    movies[i].times[j] = NULL;
                }
            }
        }
        free(movies);
        movies      = NULL;
        movie_count = 0;
    }
}

// 释放场次数据内存
static void free_show_times(void)
{
    if(show_times) {
        free(show_times);
        show_times      = NULL;
        show_time_count = 0;
    }
}

// 重置座位选择
static void reset_seat_selection(void)
{
    for(int i = 0; i < SEAT_ROWS; i++) {
        for(int j = 0; j < SEAT_COLS; j++) {
            if(seats[i][j] == SEAT_SELECTED) {
                seats[i][j] = SEAT_AVAILABLE;
            }
        }
    }
    selected_count = 0;
    memset(selected_seats, 0, sizeof(selected_seats));
}

// 从文件更新座位状态
static void update_seat_status_from_file(void)
{
    // 初始化所有座位为可选
    for(int i = 0; i < SEAT_ROWS; i++) {
        for(int j = 0; j < SEAT_COLS; j++) {
            seats[i][j] = SEAT_AVAILABLE;
        }
    }

    // 提取selected_date中的纯日期部分进行比较
    char pure_selected_date[20] = {0};
    if(strstr(selected_date, "(") != NULL) {
        // 格式如 "今天(2023-06-15)"，提取括号中的日期
        sscanf(selected_date, "%*[^(](%19[^)])", pure_selected_date);
    } else {
        // 直接使用selected_date
        strncpy(pure_selected_date, selected_date, sizeof(pure_selected_date) - 1);
    }

    // 首先从time.txt中获取座位状态
    bool showtime_found = false;
    for(int i = 0; i < show_time_count; i++) {
        // 确保电影ID匹配
        if(show_times[i].movie_id != current_movie.id) continue;

        // 确保日期匹配
        if(strcmp(show_times[i].date, pure_selected_date) != 0) continue;

        // 确保时间和影厅匹配
        if(strcmp(show_times[i].time, selected_time) != 0) continue;
        if(strcmp(show_times[i].hall, selected_hall) != 0) continue;

        // 复制座位状态
        for(int r = 0; r < SEAT_ROWS; r++) {
            for(int c = 0; c < SEAT_COLS; c++) {
                seats[r][c] = show_times[i].seat_status[r][c];
            }
        }
        showtime_found = true;
        break;
    }

    // 然后从buy.txt中更新已购买的座位状态
    FILE * file = fopen("buy.txt", "r");
    if(!file) {
        // 如果buy.txt不存在，但找到了场次信息，则直接使用场次信息中的状态
        return;
    }

    char line[512];
    char username[50], phone[20], movie_name[100], date[20], time[20], seat_info[50], ticket_number[50];
    int picked_up;
    char pickup_time[30];

    while(fgets(line, sizeof(line), file)) {
        // 移除行尾的换行符
        line[strcspn(line, "\r\n")] = 0;

        // 格式：用户名,号码,电影名,日期,场次,座位号,取票号,取票情况,取票时间
        if(sscanf(line, "%49[^,],%19[^,],%99[^,],%19[^,],%19[^,],%49[^,],%49[^,],%d,%29[^\n]", username, phone,
                  movie_name, date, time, seat_info, ticket_number, &picked_up, pickup_time) == 9) {

            // 如果是当前选择的电影、日期和场次
            if(strcmp(movie_name, current_movie.name) == 0 && strcmp(date, pure_selected_date) == 0 &&
               strcmp(time, selected_time) == 0) {

                // 解析座位号并标记为已预订
                if(strlen(seat_info) >= 2) {
                    // 格式为 "A1" 这样的座位号
                    int row = seat_info[0] - 'A';
                    int col = atoi(seat_info + 1) - 1;

                    if(row >= 0 && row < SEAT_ROWS && col >= 0 && col < SEAT_COLS) {
                        // 确保只有可用座位才能被标记为已预订
                        // 如果座位已经是已选或已预订状态，则保持原状态
                        if(seats[row][col] == SEAT_AVAILABLE) {
                            seats[row][col] = SEAT_RESERVED;
                        }
                    }
                }
            }
        }
    }

    fclose(file);
    
    // 如果没有找到对应的场次信息，但buy.txt中有相关记录
    // 需要确保这些记录的座位被标记为已预订
    if(!showtime_found) {
        // 重新打开buy.txt文件
        file = fopen("buy.txt", "r");
        if(file) {
            while(fgets(line, sizeof(line), file)) {
                line[strcspn(line, "\r\n")] = 0;

                if(sscanf(line, "%49[^,],%19[^,],%99[^,],%19[^,],%19[^,],%49[^,],%49[^,],%d,%29[^\n]", username, phone,
                          movie_name, date, time, seat_info, ticket_number, &picked_up, pickup_time) == 9) {

                    if(strcmp(movie_name, current_movie.name) == 0 && strcmp(date, pure_selected_date) == 0 &&
                       strcmp(time, selected_time) == 0) {

                        if(strlen(seat_info) >= 2) {
                            int row = seat_info[0] - 'A';
                            int col = atoi(seat_info + 1) - 1;

                            if(row >= 0 && row < SEAT_ROWS && col >= 0 && col < SEAT_COLS) {
                                // 强制设置为已预订状态，因为没有场次信息作为参考
                                seats[row][col] = SEAT_RESERVED;
                            }
                        }
                    }
                }
            }
            fclose(file);
        }
    }
}
// 更新场次剩余票数
static void update_show_time_remaining(void)
{
    // 提取selected_date中的纯日期部分进行比较
    char pure_selected_date[20] = {0};
    if(strstr(selected_date, "(") != NULL) {
        // 格式如 "今天(2023-06-15)"，提取括号中的日期
        sscanf(selected_date, "%*[^(](%19[^)])", pure_selected_date);
    } else {
        // 直接使用selected_date
        strncpy(pure_selected_date, selected_date, sizeof(pure_selected_date) - 1);
    }
    
    // 查找对应场次并更新剩余票数
    for(int i = 0; i < show_time_count; i++) {
        if(show_times[i].movie_id == current_movie.id && strcmp(show_times[i].date, pure_selected_date) == 0 &&
           strcmp(show_times[i].hall, selected_hall) == 0 && strcmp(show_times[i].time, selected_time) == 0) {
            
            // 更新剩余座位数
            show_times[i].remaining_seats -= selected_count;

            // 更新座位状态 - 只更新当前选中的座位
            for(int s = 0; s < selected_count; s++) {
                int row = selected_seats[s] / SEAT_COLS;
                int col = selected_seats[s] % SEAT_COLS;
                if(row < SEAT_ROWS && col < SEAT_COLS) {
                    // 确保只将可用座位标记为已预订
                    if(show_times[i].seat_status[row][col] == SEAT_AVAILABLE) {
                        show_times[i].seat_status[row][col] = SEAT_RESERVED;
                    }
                }
            }

            // 更新到文件
            FILE * file = fopen("time.txt", "w");
            if(file) {
                for(int j = 0; j < show_time_count; j++) {
                    // 写入基本信息
                    fprintf(file, "%d,%s,%s,%s,%d,%d", show_times[j].movie_id, show_times[j].date, show_times[j].hall,
                            show_times[j].time, show_times[j].total_seats, show_times[j].remaining_seats);

                    // 写入座位状态信息
                    for(int r = 0; r < SEAT_ROWS; r++) {
                        for(int c = 0; c < SEAT_COLS; c++) {
                            fprintf(file, ",%d", show_times[j].seat_status[r][c]);
                        }
                    }
                    fprintf(file, "\n");
                }
                fclose(file);
            }
            break;
        }
    }
}
// 初始化购票屏幕
void buy_tickets_screen_init_new(void)
{
    LV_LOG_USER("Initializing ticket screen");

    // 如果屏幕已存在，直接显示
    if(ticket_screen) {
        lv_obj_clear_flag(ticket_screen, LV_OBJ_FLAG_HIDDEN);
        lv_scr_load(ticket_screen);
        return;
    }

    // 初始化日期选项
    LV_LOG_USER("Initializing date options");
    init_date_options();

    // 从文件加载数据
    LV_LOG_USER("Loading movies from file");
    bool movies_loaded = load_movies_from_file();
    if(!movies_loaded) {
        LV_LOG_USER("Failed to load movies");
    }

    // 生成场次安排
    LV_LOG_USER("Generating show times");
    generate_show_times();

    LV_LOG_USER("Loading show times from file");
    bool showtimes_loaded = load_show_times_from_file();
    if(!showtimes_loaded) {
        LV_LOG_USER("Failed to load show times");
    }

    if(!movies_loaded || !showtimes_loaded) {
        lv_obj_t * err_msg = lv_msgbox_create(NULL, "错误", "无法加载电影信息", NULL, false);
        lv_obj_center(err_msg);
        return;
    }

    // 创建新屏幕
    ticket_screen = lv_obj_create(NULL);
    lv_obj_set_size(ticket_screen, SCREEN_WIDTH, SCREEN_HEIGHT);         // 设置屏幕大小
    lv_obj_set_style_bg_color(ticket_screen, lv_color_hex(0xf5f5f5), 0); // 设置背景颜色
    lv_obj_clear_flag(ticket_screen, LV_OBJ_FLAG_SCROLLABLE);            // 取消滚动

    // 创建顶部标题栏
    lv_obj_t * top_bar = lv_obj_create(ticket_screen);
    lv_obj_set_size(top_bar, SCREEN_WIDTH, 50);                    // 设置标题栏大小
    lv_obj_set_style_bg_color(top_bar, lv_color_hex(0x333333), 0); // 设置标题栏背景颜色
    lv_obj_set_style_border_width(top_bar, 0, 0);                  // 取消标题栏边框
    lv_obj_clear_flag(top_bar, LV_OBJ_FLAG_SCROLLABLE);            // 取消滚动

    lv_obj_t * title = lv_label_create(top_bar);
    lv_label_set_text(title, "电影购票");                                  // 标题
    lv_obj_set_style_text_color(title, lv_color_hex(0xffffff), 0);         // 标题颜色
    lv_obj_set_style_text_font(title, &SourceHanSansCN_Light_2_16_all, 0); // 标题字体
    lv_obj_center(title);                                                  // 标题居中

    // 创建返回按钮
    create_back_button(top_bar);

    // 初始化内容区域
    clear_content_area();

    // 显示电影选择页面
    show_movie_selection_page();

    // 加载屏幕
    lv_scr_load(ticket_screen);

    LV_LOG_USER("Ticket screen initialized successfully");
}

// 清除内容区域
static void clear_content_area()
{
    // 简化清理逻辑，只删除content_area
    if(content_area) {
        lv_obj_del(content_area);
    }
    content_area = lv_obj_create(ticket_screen);                     // 创建内容区域
    lv_obj_set_size(content_area, SCREEN_WIDTH, SCREEN_HEIGHT - 50); // 50是顶部标题栏高度
    lv_obj_align(content_area, LV_ALIGN_BOTTOM_MID, 0, 0);           // 设置内容区域位置
    lv_obj_set_style_bg_opa(content_area, LV_OPA_TRANSP, 0);         // 透明
    lv_obj_set_style_border_width(content_area, 0, 0);               // 取消边框
    lv_obj_clear_flag(content_area, LV_OBJ_FLAG_SCROLLABLE);         // 取消滚动
}

// 创建返回按钮
static lv_obj_t * create_back_button(lv_obj_t * parent)
{
    lv_obj_t * btn = lv_btn_create(parent);
    lv_obj_set_size(btn, 80, 35);
    lv_obj_align(btn, LV_ALIGN_LEFT_MID, 0, 0); // 设置按钮位置
    lv_obj_set_style_bg_color(btn, lv_color_hex(0x666666), 0);
    lv_obj_set_style_radius(btn, 4, 0);
    set_btn_transition(btn);

    lv_obj_t * label = lv_label_create(btn);
    lv_label_set_text(label, "返回");
    lv_obj_center(label);

    lv_obj_add_event_cb(btn, back_btn_handler, LV_EVENT_CLICKED, NULL);
    return btn;
}
// 返回按钮回调
static void back_btn_handler(lv_event_t * e)
{
    if(lv_event_get_code(e) == LV_EVENT_CLICKED) {
        switch(current_page_type) {
            case PAGE_MOVIE_SELECTION:
                // 返回主菜单 - 隐藏电影选择页面并显示主菜单
                LV_LOG_USER("Hiding ticket screen and showing main menu");

                // 清空选择状态
                reset_seat_selection();
                selected_count = 0;
                memset(selected_seats, 0, sizeof(selected_seats));
                selected_date[0] = '\0';
                selected_time[0] = '\0';
                selected_hall[0] = '\0';

                // 隐藏购票界面
                if(ticket_screen) {
                    lv_obj_add_flag(ticket_screen, LV_OBJ_FLAG_HIDDEN);
                }

                // 显示主菜单
                extern lv_obj_t * menu_screen;
                extern bool menu_screen_hidden;
                if(menu_screen) {
                    lv_obj_clear_flag(menu_screen, LV_OBJ_FLAG_HIDDEN);
                    menu_screen_hidden = false;
                    lv_scr_load_anim(menu_screen, LV_SCR_LOAD_ANIM_FADE_ON, 300, 0, false);
                }

                // 恢复主菜单定时器
                extern lv_timer_t * time_timer;
                if(time_timer) {
                    lv_timer_resume(time_timer);
                }
                break;

            case PAGE_TIME_SELECTION:
                // 返回电影选择页面
                LV_LOG_USER("Returning to movie selection from time selection");
                show_movie_selection_page();
                break;

            case PAGE_SEAT_SELECTION:
                // 返回场次选择页面
                LV_LOG_USER("Returning to time selection from seat selection");
                show_time_selection_page(); // 返回场次选择页面
                reset_seat_selection();     // 重置选座状态
                break;
        }
    }
}
// 显示电影选择页面
static void show_movie_selection_page()
{
    current_page_type = PAGE_MOVIE_SELECTION; // 更新当前页面类型

    // 隐藏其他页面
    if(time_selection_page) {
        lv_obj_add_flag(time_selection_page, LV_OBJ_FLAG_HIDDEN);
    }

    if(seat_selection_page) {
        lv_obj_add_flag(seat_selection_page, LV_OBJ_FLAG_HIDDEN);
    }

    // 如果电影选择页面不存在，则创建它
    if(!movie_selection_page) {
        // 创建页面容器
        movie_selection_page = lv_obj_create(content_area);
        lv_obj_set_size(movie_selection_page, SCREEN_WIDTH, SCREEN_HEIGHT - 50); // 设置页面大小
        lv_obj_clear_flag(movie_selection_page, LV_OBJ_FLAG_CLICKABLE);          // 取消点击
        lv_obj_set_style_bg_opa(movie_selection_page, LV_OPA_TRANSP, 0);         // 设置背景透明
        lv_obj_set_style_border_width(movie_selection_page, 0, 0);               // 取消边框
        lv_obj_align(content_area, LV_ALIGN_TOP_MID, 0, 30);                     // 设置位置

        // 页面标题
        lv_obj_t * page_title = lv_label_create(movie_selection_page);              // 创建标题标签
        lv_label_set_text(page_title, "请选择电影");                                // 设置标题文本
        lv_obj_set_style_text_font(page_title, &SourceHanSansCN_Light_2_16_all, 0); // 设置字体
        lv_obj_align(page_title, LV_ALIGN_TOP_MID, 0, 10);                          // 设置标题位置

        // 创建滚动容器
        lv_obj_t * scroll_container = lv_obj_create(movie_selection_page);
        lv_obj_set_size(scroll_container, SCREEN_WIDTH - 30, SCREEN_HEIGHT - 30); // 设置滚动容器大小
        lv_obj_align(scroll_container, LV_ALIGN_TOP_MID, 0, 20);                  // 设置滚动容器位置
        lv_obj_set_style_bg_opa(scroll_container, LV_OPA_TRANSP, 0);              // 取消背景
        lv_obj_set_style_border_width(scroll_container, 0, 0);                    // 取消边框
        lv_obj_set_scrollbar_mode(scroll_container, LV_SCROLLBAR_MODE_AUTO);      // 设置滚动条

        // 创建列表布局
        lv_obj_t * list = lv_list_create(scroll_container);
        lv_obj_set_size(list, lv_pct(100), lv_pct(100)); // 设置列表大小
        lv_obj_set_style_bg_opa(list, LV_OPA_TRANSP, 0); // 取消背景
        lv_obj_set_style_border_width(list, 0, 0);       // 取消边框

        // 添加电影列表项
        for(int i = 0; i < movie_count; i++) {
            // 创建列表项
            lv_obj_t * list_btn = lv_list_add_btn(list, NULL, movies[i].name);
            lv_obj_set_height(list_btn, 80);
            lv_obj_set_style_bg_color(list_btn, lv_color_hex(0x0099ff), 0);
            lv_obj_set_style_radius(list_btn, 6, 0);
            set_btn_transition(list_btn);

            // 添加时长信息
            lv_obj_t * duration_label = lv_label_create(list_btn);
            lv_label_set_text_fmt(duration_label, "时长: %s | 票价: %d元", movies[i].duration, movies[i].price);
            lv_obj_set_style_text_color(duration_label, lv_color_hex(0xffffff), 0);
            lv_obj_align(duration_label, LV_ALIGN_BOTTOM_LEFT, 20, -10);

            // 存储电影索引
            int * index = lv_mem_alloc(sizeof(int));
            *index      = i;
            lv_obj_set_user_data(list_btn, index);

            // 添加点击事件
            lv_obj_add_event_cb(list_btn, movie_select_handler, LV_EVENT_CLICKED, NULL);
        }
    } else {
        // 如果页面已存在，直接显示
        lv_obj_clear_flag(movie_selection_page, LV_OBJ_FLAG_HIDDEN);
    }
}
// 显示场次选择页面
static void show_time_selection_page()
{
    current_page_type = PAGE_TIME_SELECTION;

    // 隐藏其他页面
    if(movie_selection_page) {
        lv_obj_add_flag(movie_selection_page, LV_OBJ_FLAG_HIDDEN);
    }

    if(seat_selection_page) {
        lv_obj_add_flag(seat_selection_page, LV_OBJ_FLAG_HIDDEN);
    }

    // 如果没有选中日期，则默认选择第一个日期
    if(selected_date[0] == '\0' && sizeof(date_options) > 0) {
        strcpy(selected_date, date_options[0].display);
    }

    // 如果场次选择页面已存在，直接显示并更新内容
    if(time_selection_page) {
        lv_obj_clear_flag(time_selection_page, LV_OBJ_FLAG_HIDDEN);
        
        // 更新电影标题
        lv_obj_t * movie_title = lv_obj_get_child(time_selection_page, 0); // 第一个子对象是电影标题
        if(movie_title && lv_obj_check_type(movie_title, &lv_label_class)) {
            lv_label_set_text(movie_title, current_movie.name);
        }
        
        // 更新时长信息
        lv_obj_t * duration_label = lv_obj_get_child(time_selection_page, 1); // 第二个子对象是时长信息
        if(duration_label && lv_obj_check_type(duration_label, &lv_label_class)) {
            lv_label_set_text_fmt(duration_label, "时长: %s | 票价: %d元", current_movie.duration, current_movie.price);
        }
        
        // 更新日期按钮状态
        lv_obj_t * date_container = lv_obj_get_child(time_selection_page, 2); // 第三个子对象是日期容器
        if(date_container) {
            for(int i = 0; i < 3 && i < lv_obj_get_child_cnt(date_container); i++) {
                lv_obj_t * date_btn = lv_obj_get_child(date_container, i);
                if(date_btn) {
                    // 根据是否为当前选中日期设置按钮颜色
                    if(strcmp(selected_date, date_options[i].display) == 0) {
                        lv_obj_set_style_bg_color(date_btn, lv_color_hex(0x00cc00), 0); // 选中状态为绿色
                        prev_date_btn = date_btn;
                    } else {
                        lv_obj_set_style_bg_color(date_btn, lv_color_hex(0x0099ff), 0); // 未选中状态为蓝色
                    }
                }
            }
        }
        
        // 更新场次按钮
        lv_obj_t * time_container = lv_obj_get_child(time_selection_page, 4); // 第五个子对象是场次容器
        if(time_container) {
            // 清除现有的场次按钮并释放用户数据内存
            int child_count = lv_obj_get_child_cnt(time_container);
            for (int i = 0; i < child_count; i++) {
                lv_obj_t * child = lv_obj_get_child(time_container, 0); // 总是获取第一个子对象
                if (child) {
                    void * user_data = lv_obj_get_user_data(child);
                    if (user_data) {
                        lv_mem_free(user_data);
                        lv_obj_set_user_data(child, NULL);
                    }
                    lv_obj_del(child); // 删除对象
                }
            }
            
            // 重新添加符合当前条件的场次按钮
            add_showtime_buttons(time_container);
        }
        return;
    }

    // 创建页面容器
    time_selection_page = lv_obj_create(content_area);
    lv_obj_set_size(time_selection_page, SCREEN_WIDTH, SCREEN_HEIGHT - 50); // 设置页面大小
    lv_obj_clear_flag(time_selection_page, LV_OBJ_FLAG_CLICKABLE);          // 取消点击
    lv_obj_set_style_bg_opa(time_selection_page, LV_OPA_TRANSP, 0);         // 设置背景透明
    lv_obj_set_style_border_width(time_selection_page, 0, 0);               // 取消边框
    lv_obj_align(content_area, LV_ALIGN_TOP_MID, 0, 30);                    // 设置位置

    // 电影标题
    lv_obj_t * movie_title = lv_label_create(time_selection_page);
    lv_label_set_text(movie_title, current_movie.name);                          // 设置电影标题
    lv_obj_set_style_text_font(movie_title, &SourceHanSansCN_Light_2_16_all, 0); // 设置字体
    lv_obj_align(movie_title, LV_ALIGN_TOP_MID, 0, 0);                           // 设置标题位置

    // 时长信息
    lv_obj_t * duration_label = lv_label_create(time_selection_page); // 创建时长信息标签
    lv_label_set_text_fmt(duration_label, "时长: %s | 票价: %d元", current_movie.duration,
                          current_movie.price);                             // 设置时长信息
    lv_obj_set_style_text_color(duration_label, lv_color_hex(0x666666), 0); // 设置颜色
    lv_obj_align(duration_label, LV_ALIGN_TOP_MID, 0, 20);                  // 设置位置

    // 日期选择容器
    lv_obj_t * date_container = lv_obj_create(time_selection_page); // 创建日期选择容器
    lv_obj_set_size(date_container, SCREEN_WIDTH - 40, 60);         // 设置大小
    lv_obj_align(date_container, LV_ALIGN_TOP_MID, 0, 50);          // 设置位置
    lv_obj_set_style_bg_opa(date_container, LV_OPA_TRANSP, 0);      // 取消背景
    lv_obj_set_style_border_width(date_container, 0, 0);            // 取消边框
    lv_obj_set_layout(date_container, LV_LAYOUT_FLEX);              // 设置布局
    lv_obj_set_flex_flow(date_container, LV_FLEX_FLOW_ROW);         // 设置布局 列
    lv_obj_set_flex_align(date_container, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER,
                          LV_FLEX_ALIGN_CENTER);               // 设置对齐
    lv_obj_set_style_pad_column(date_container, 20, 0);        // 设置列间距
    lv_obj_clear_flag(date_container, LV_OBJ_FLAG_SCROLLABLE); // 取消滚动

    // 添加日期选择按钮
    for(int i = 0; i < 3; i++) {
        lv_obj_t * date_btn = lv_btn_create(date_container);
        lv_obj_set_size(date_btn, 180, 50);
        // 根据是否为当前选中日期设置按钮颜色
        if(strcmp(selected_date, date_options[i].display) == 0) {
            lv_obj_set_style_bg_color(date_btn, lv_color_hex(0x00cc00), 0); // 选中状态为绿色
            prev_date_btn = date_btn;
        } else {
            lv_obj_set_style_bg_color(date_btn, lv_color_hex(0x0099ff), 0); // 未选中状态为蓝色
        }
        lv_obj_set_style_radius(date_btn, 6, 0);
        set_btn_transition(date_btn);

        lv_obj_t * label = lv_label_create(date_btn);
        lv_label_set_text(label, date_options[i].display);
        lv_obj_center(label);

        // 存储日期索引
        int * date_idx = lv_mem_alloc(sizeof(int));
        if (date_idx) {
            *date_idx = i;
            lv_obj_set_user_data(date_btn, date_idx);
        }

        lv_obj_add_event_cb(date_btn, date_select_handler, LV_EVENT_CLICKED, NULL);
    }

    // 场次列表标题
    lv_obj_t * time_title = lv_label_create(time_selection_page);       // 创建场次列表标题
    lv_label_set_text(time_title, "请选择场次");                        // 设置标题文本
    lv_obj_set_style_text_color(time_title, lv_color_hex(0x666666), 0); // 设置颜色
    lv_obj_align(time_title, LV_ALIGN_TOP_MID, 0, 110);                 // 设置位置

    // 场次容器
    lv_obj_t * time_container = lv_obj_create(time_selection_page);
    lv_obj_set_size(time_container, SCREEN_WIDTH - 60, SCREEN_HEIGHT - 140); // 设置大小
    lv_obj_align(time_container, LV_ALIGN_TOP_MID, 0, 120);                  // 设置位置
    lv_obj_set_style_bg_opa(time_container, LV_OPA_TRANSP, 0);               // 取消背景
    lv_obj_set_style_border_width(time_container, 0, 0);                     // 取消边框
    lv_obj_set_layout(time_container, LV_LAYOUT_FLEX);                       // 设置布局
    lv_obj_set_flex_flow(time_container, LV_FLEX_FLOW_COLUMN);               // 设置布局 行
    lv_obj_set_style_pad_row(time_container, 10, 0);                         // 设置行间距
    lv_obj_set_scrollbar_mode(time_container, LV_SCROLLBAR_MODE_AUTO);       // 显示滚动条

    // 添加当前电影且符合选中日期的场次按钮
    add_showtime_buttons(time_container);
}
// 添加场次按钮的函数
static void add_showtime_buttons(lv_obj_t * parent)
{
    // 添加当前电影且符合选中日期的场次按钮
    for(int i = 0; i < show_time_count; i++) {
        // 只显示当前电影的场次
        if(show_times[i].movie_id != current_movie.id) continue;

        // 构造要匹配的日期字符串 (格式: YYYY-MM-DD)
        char target_date[20];
        bool date_found = false;

        // 从date_options中获取当前选中日期的实际日期部分
        for(int j = 0; j < 3; j++) {
            if(strcmp(selected_date, date_options[j].display) == 0) {
                snprintf(target_date, sizeof(target_date), "%d-%02d-%02d", date_options[j].year, date_options[j].month,
                         date_options[j].day);
                date_found = true;
                break;
            }
        }

        // 如果没有找到匹配的日期，则跳过这个场次
        if(!date_found) continue;

        // 检查日期是否匹配
        if(strcmp(show_times[i].date, target_date) != 0) continue;

        // 如果执行到这里，说明场次符合电影和日期条件
        int remaining = show_times[i].remaining_seats;

        LV_LOG_USER("Creating time button: movie_id=%d, date=%s, time=%s, hall=%s, remaining=%d",
                    show_times[i].movie_id, show_times[i].date, show_times[i].time, show_times[i].hall, remaining);

        lv_obj_t * time_btn = lv_btn_create(parent);
        lv_obj_set_size(time_btn, lv_pct(100), 60);
        lv_obj_set_style_bg_color(time_btn, remaining > 0 ? lv_color_hex(0x0099ff) : lv_color_hex(0xcccccc), 0);
        lv_obj_set_style_radius(time_btn, 6, 0);
        set_btn_transition(time_btn);

        lv_obj_t * label = lv_label_create(time_btn);
        lv_label_set_text_fmt(label, "%s | 影厅:%s | 剩余票数: %d", show_times[i].time, show_times[i].hall, remaining);
        lv_obj_center(label);

        // 存储场次索引
        int * time_idx = lv_mem_alloc(sizeof(int));
        if (time_idx) {
            *time_idx = i;
            lv_obj_set_user_data(time_btn, time_idx);
        } else {
            LV_LOG_USER("Failed to allocate memory for time index");
        }

        // 只有有余票的场次才可点击
        if(remaining > 0 && time_idx) {  // 只有在内存分配成功时才添加事件处理
            lv_obj_add_event_cb(time_btn, time_select_handler, LV_EVENT_CLICKED, NULL);
            LV_LOG_USER("Time button is clickable");
        } else {
            lv_obj_clear_flag(time_btn, LV_OBJ_FLAG_CLICKABLE);
            LV_LOG_USER("Time button is NOT clickable (no remaining seats or memory allocation failed)");
        }
    }
}
// 显示座位选择页面
static void show_seat_selection_page()
{
    current_page_type = PAGE_SEAT_SELECTION;

    // 隐藏其他页面
    if(movie_selection_page) {
        lv_obj_add_flag(movie_selection_page, LV_OBJ_FLAG_HIDDEN);
    }

    if(time_selection_page) {
        lv_obj_add_flag(time_selection_page, LV_OBJ_FLAG_HIDDEN);
    }

    // 如果座位选择页面已存在，直接显示并更新座位状态
    if(seat_selection_page) {
        lv_obj_clear_flag(seat_selection_page, LV_OBJ_FLAG_HIDDEN);

        // 更新头部信息
        lv_obj_t * header_info = lv_obj_get_child(seat_selection_page, 0); // 获取头部信息标签
        if(header_info && lv_obj_check_type(header_info, &lv_label_class)) {
            // 提取selected_date中的纯日期部分进行显示
            char display_date[20] = {0};
            if(strstr(selected_date, "(") != NULL) {
                // 格式如 "今天(2023-06-15)"，提取括号中的日期用于显示
                sscanf(selected_date, "%*[^(](%19[^)])", display_date);
            } else {
                // 直接使用selected_date
                strncpy(display_date, selected_date, sizeof(display_date) - 1);
            }
            
            lv_label_set_text_fmt(header_info, "%s | %s | %s | 影厅: %s", 
                                current_movie.name, display_date,
                                selected_time, selected_hall);
        }

        // 更新座位状态
        update_seat_status_from_file();

        // 更新座位显示
        lv_obj_t * seat_container = lv_obj_get_child(seat_selection_page, -1); // 获取座位容器
        if(seat_container) {
            seat_container = lv_obj_get_child(seat_container, -1); // 获取座位网格容器
            if(seat_container) {
                // 清除现有的座位
                while(lv_obj_get_child_cnt(seat_container) > 0) {
                    lv_obj_del(lv_obj_get_child(seat_container, 0));
                }
                
                // 重新创建座位
                create_seats(seat_container);
            }
        }
        return;
    }

    // 创建页面容器
    seat_selection_page = lv_obj_create(content_area);
    lv_obj_set_size(seat_selection_page, SCREEN_WIDTH, SCREEN_HEIGHT - 50); // 设置大小
    lv_obj_clear_flag(seat_selection_page, LV_OBJ_FLAG_CLICKABLE);          // 取消点击
    lv_obj_set_style_bg_opa(seat_selection_page, LV_OPA_TRANSP, 0);         // 设置背景透明
    lv_obj_set_style_border_width(seat_selection_page, 0, 0);               // 取消边框
    lv_obj_align(content_area, LV_ALIGN_TOP_MID, 0, 30);                    // 设置位置

    // 头部信息
    lv_obj_t * header_info = lv_label_create(seat_selection_page);
    
    // 提取selected_date中的纯日期部分进行显示
    char display_date[20] = {0};
    if(strstr(selected_date, "(") != NULL) {
        // 格式如 "今天(2023-06-15)"，提取括号中的日期用于显示
        sscanf(selected_date, "%*[^(](%19[^)])", display_date);
    } else {
        // 直接使用selected_date
        strncpy(display_date, selected_date, sizeof(display_date) - 1);
    }
    
    lv_label_set_text_fmt(header_info, "%s | %s | %s | 影厅: %s", current_movie.name, display_date,
                          selected_time,                                         // 显示电影名称、日期、时间、影厅
                          selected_hall);                                        // 显示影厅
    lv_obj_set_style_text_font(header_info, &SourceHanSansCN_Light_2_16_all, 0); // 设置字体
    lv_obj_align(header_info, LV_ALIGN_TOP_MID, 0, 0);                           // 设置位置

    // 图例说明
    lv_obj_t * legend = lv_obj_create(seat_selection_page);
    lv_obj_set_size(legend, 600, 40);                                                 // 设置大小
    lv_obj_align(legend, LV_ALIGN_TOP_MID, 30, 20);                                   // 设置位置
    lv_obj_set_style_bg_opa(legend, LV_OPA_TRANSP, 0);                                // 设置背景透明
    lv_obj_set_style_border_width(legend, 0, 0);                                      // 取消边框
    lv_obj_set_layout(legend, LV_LAYOUT_FLEX);                                        // 设置布局
    lv_obj_set_flex_flow(legend, LV_FLEX_FLOW_ROW);                                   // 设置布局为Flex
    lv_obj_set_flex_align(legend, LV_ALIGN_CENTER, LV_ALIGN_CENTER, LV_ALIGN_CENTER); // 设置对齐
    lv_obj_set_style_pad_column(legend, 40, 0);                                       // 设置列间距
    lv_obj_clear_flag(legend, LV_OBJ_FLAG_SCROLLABLE);                                // 取消滚动

    // 可选座位图例
    lv_obj_t * avail_box = lv_obj_create(legend);
    lv_obj_set_size(avail_box, 20, 20);
    lv_obj_set_style_bg_color(avail_box, lv_color_hex(0x00cc00), 0);
    lv_obj_clear_flag(avail_box, LV_OBJ_FLAG_SCROLLABLE); // 取消滚动

    lv_obj_t * avail_label = lv_label_create(legend);
    lv_label_set_text(avail_label, "可选座位");

    // 已选座位图例
    lv_obj_t * select_box = lv_obj_create(legend);
    lv_obj_set_size(select_box, 20, 20);
    lv_obj_set_style_bg_color(select_box, lv_color_hex(0xff9900), 0);
    lv_obj_clear_flag(select_box, LV_OBJ_FLAG_SCROLLABLE); // 取消滚动

    lv_obj_t * select_label = lv_label_create(legend);
    lv_label_set_text(select_label, "已选座位");

    // 已售座位图例
    lv_obj_t * sold_box = lv_obj_create(legend);
    lv_obj_set_size(sold_box, 20, 20);
    lv_obj_set_style_bg_color(sold_box, lv_color_hex(0xcc0000), 0);
    lv_obj_clear_flag(sold_box, LV_OBJ_FLAG_SCROLLABLE); // 取消滚动

    lv_obj_t * sold_label = lv_label_create(legend);
    lv_label_set_text(sold_label, "已售座位");

    // 屏幕区域
    lv_obj_t * screen = lv_obj_create(seat_selection_page);
    lv_obj_set_size(screen, 500, 30);                             // 设置大小
    lv_obj_align(screen, LV_ALIGN_TOP_MID, 0, 70);                // 设置位置
    lv_obj_set_style_bg_color(screen, lv_color_hex(0xcccccc), 0); // 设置背景颜色
    lv_obj_set_style_radius(screen, 20, 0);                       // 设置圆角
    lv_obj_set_style_border_width(screen, 0, 0);                  // 取消边框
    lv_obj_clear_flag(screen, LV_OBJ_FLAG_SCROLLABLE);            // 取消滚动

    lv_obj_t * screen_label = lv_label_create(screen);
    lv_label_set_text(screen_label, "屏幕"); // 显示"屏幕"
    lv_obj_center(screen_label);             // 居中

    // 更新座位状态
    update_seat_status_from_file();

    // 座位容器
    lv_obj_t * seat_container = lv_obj_create(seat_selection_page);
    lv_obj_set_size(seat_container, SCREEN_WIDTH - 300, SCREEN_HEIGHT - 200); // 设置大小
    lv_obj_align(seat_container, LV_ALIGN_TOP_MID, 0, 100);                   // 设置位置居中
    lv_obj_set_style_bg_opa(seat_container, LV_OPA_TRANSP, 0);                // 设置背景透明
    lv_obj_set_style_border_width(seat_container, 0, 0);                      // 取消边框
    lv_obj_set_style_pad_all(seat_container, 5, 0);                           // 设置内边距
    lv_obj_set_style_pad_row(seat_container, 5, 0);                           // 设置行间距
    lv_obj_set_style_pad_column(seat_container, 5, 0);                        // 设置列间距

    // 设置网格布局
    static lv_coord_t col_dsc[SEAT_COLS + 1]; // 列描述
    static lv_coord_t row_dsc[SEAT_ROWS + 1];

    for(int i = 0; i < SEAT_COLS; i++) {
        col_dsc[i] = 50;
    }
    col_dsc[SEAT_COLS] = LV_GRID_TEMPLATE_LAST;

    for(int i = 0; i < SEAT_ROWS; i++) {
        row_dsc[i] = 50;
    }
    row_dsc[SEAT_ROWS] = LV_GRID_TEMPLATE_LAST;

    lv_obj_set_layout(seat_container, LV_LAYOUT_GRID);                  // 设置布局为网格
    lv_obj_set_style_grid_column_dsc_array(seat_container, col_dsc, 0); // 设置列描述
    lv_obj_set_style_grid_row_dsc_array(seat_container, row_dsc, 0);    // 设置行描述

    // 创建座位 - 移除了行标签和列标签
    create_seats(seat_container);

    // 确认按钮
    lv_obj_t * confirm_btn = lv_btn_create(seat_selection_page);
    lv_obj_set_size(confirm_btn, 100, 40);                             // 设置按钮大小
    lv_obj_align(confirm_btn, LV_ALIGN_BOTTOM_RIGHT, -20, -10);        // 设置按钮位置
    lv_obj_set_style_bg_color(confirm_btn, lv_color_hex(0xff6600), 0); // 设置按钮颜色
    lv_obj_set_style_radius(confirm_btn, 6, 0);                        // 设置按钮圆角
    set_btn_transition(confirm_btn);                                   // 设置按钮动画

    lv_obj_t * confirm_label = lv_label_create(confirm_btn);
    lv_label_set_text(confirm_label, "确认购票");
    lv_obj_center(confirm_label); // 设置文字居中

    lv_obj_add_event_cb(confirm_btn, confirm_purchase, LV_EVENT_CLICKED, NULL); // 添加点击事件
}

// 电影选择事件
static void movie_select_handler(lv_event_t * e)
{
    if(lv_event_get_code(e) == LV_EVENT_CLICKED) {
        lv_obj_t * btn = lv_event_get_target(e);
        
        // 检查按钮对象是否有效
        if (!btn) {
            LV_LOG_USER("Invalid movie button object");
            return;
        }
        
        // 检查用户数据是否存在
        void * user_data = lv_obj_get_user_data(btn);
        if (!user_data) {
            LV_LOG_USER("Movie button user data is NULL");
            return;
        }
        
        current_movie_index = *(int *)user_data;
        
        // 检查索引是否有效
        if(current_movie_index < 0 || current_movie_index >= movie_count) {
            LV_LOG_USER("Invalid movie index: %d, movie_count: %d", current_movie_index, movie_count);
            return;
        }
        
        // 确保movies数组有效
        if (!movies) {
            LV_LOG_USER("Movies array is NULL");
            return;
        }

        current_movie = movies[current_movie_index];
        
        // 不再设置selected_hall，因为影厅信息从time.txt获取
        // strcpy(selected_hall, current_movie.hall);

        // 初始化选中日期为第一个日期选项
        if(sizeof(date_options) > 0) {
            strcpy(selected_date, date_options[0].display);
        }

        // 进入场次选择页面
        show_time_selection_page();
    }
}
// 日期选择事件
static void date_select_handler(lv_event_t * e)
{
    if(lv_event_get_code(e) == LV_EVENT_CLICKED) {
        lv_obj_t * btn = lv_event_get_target(e);
        
        // 检查按钮对象是否有效
        if (!btn) {
            LV_LOG_USER("Invalid date button object");
            return;
        }
        
        // 检查用户数据是否存在
        void * user_data = lv_obj_get_user_data(btn);
        if (!user_data) {
            LV_LOG_USER("Date button user data is NULL");
            return;
        }
        
        int date_idx = *(int *)user_data;

        // 检查索引是否有效
        if(date_idx < 0 || date_idx >= 3) {
            LV_LOG_USER("Invalid date index: %d", date_idx);
            return;
        }

        // 更新按钮样式
        if(prev_date_btn) {
            lv_obj_set_style_bg_color(prev_date_btn, lv_color_hex(0x0099ff), 0);
        }
        lv_obj_set_style_bg_color(btn, lv_color_hex(0x00cc00), 0);
        prev_date_btn = btn;

        // 保存选中的日期
        strcpy(selected_date, date_options[date_idx].display);

        // 更新场次按钮 - 查找并更新场次容器中的内容
        if(time_selection_page) {
            // 查找场次容器（第5个子对象）
            lv_obj_t * time_container = lv_obj_get_child(time_selection_page, 4);
            if(time_container) {
                // 清除现有的场次按钮
                while(lv_obj_get_child_cnt(time_container) > 0) {
                    lv_obj_del(lv_obj_get_child(time_container, 0));
                }
                
                // 重新添加符合当前条件的场次按钮
                add_showtime_buttons(time_container);
            }
        }
    }
}
// 场次选择事件
static void time_select_handler(lv_event_t * e)
{
    if(lv_event_get_code(e) == LV_EVENT_CLICKED) {
        lv_obj_t * btn = lv_event_get_target(e);
        
        // 检查按钮对象是否有效
        if (!btn) {
            LV_LOG_USER("Invalid button object");
            return;
        }
        
        // 检查用户数据是否存在
        void * user_data = lv_obj_get_user_data(btn);
        if (!user_data) {
            LV_LOG_USER("Button user data is NULL");
            return;
        }
        
        int time_idx = *(int *)user_data;

        LV_LOG_USER("Time selected: index=%d", time_idx);

        // 检查索引是否有效
        if(time_idx < 0 || time_idx >= show_time_count) {
            LV_LOG_USER("Invalid time index: %d, show_time_count: %d", time_idx, show_time_count);
            return;
        }

        // 确保show_times数组有效
        if (!show_times) {
            LV_LOG_USER("show_times array is NULL");
            return;
        }

        // 保存选择的场次信息
        strcpy(selected_time, show_times[time_idx].time);
        strcpy(selected_hall, show_times[time_idx].hall);
        strcpy(selected_date, show_times[time_idx].date); // 保存日期信息

        LV_LOG_USER("Selected time: %s, hall: %s, date: %s", selected_time, selected_hall, selected_date);

        // 更新按钮样式（添加安全检查）
        if(prev_selected_time_btn) {
            lv_obj_set_style_bg_color(prev_selected_time_btn, lv_color_hex(0x0099ff), 0);
        }
        
        if (btn) {
            lv_obj_set_style_bg_color(btn, lv_color_hex(0x00cc00), 0);
            prev_selected_time_btn = btn;
        }

        // 进入座位选择页面
        show_seat_selection_page();
    }
}
// 座位点击事件
static void seat_click_handler(lv_event_t * e)
{
    if(lv_event_get_code(e) == LV_EVENT_CLICKED) {
        lv_obj_t * seat = lv_event_get_target(e);
        int * coord     = (int *)lv_obj_get_user_data(seat);
        int row = coord[0], col = coord[1];

        // 根据座位状态设置样式
        if(seats[row][col] == SEAT_AVAILABLE) {
            // 最多选择10个座位
            if(selected_count < MAX_SELECTED_SEATS) {
                seats[row][col] = SEAT_SELECTED;
                lv_obj_set_style_bg_color(seat, lv_color_hex(0xff9900), 0);
                selected_seats[selected_count++] = row * SEAT_COLS + col;
            }
        } else if(seats[row][col] == SEAT_SELECTED) {
            seats[row][col] = SEAT_AVAILABLE;
            lv_obj_set_style_bg_color(seat, lv_color_hex(0x00cc00), 0);

            // 从已选列表中移除
            for(int i = 0; i < selected_count; i++) {
                if(selected_seats[i] == row * SEAT_COLS + col) {
                    for(int j = i; j < selected_count - 1; j++) {
                        selected_seats[j] = selected_seats[j + 1];
                    }
                    selected_count--;
                    break;
                }
            }
        }
        // SEAT_RESERVED状态的座位不响应点击事件（在创建时已设置为不可点击）
    }
}

// 更新座位显示状态
static void update_seat_display(lv_obj_t * seat_container)
{
    for(int i = 0; i < lv_obj_get_child_cnt(seat_container); i++) {
        lv_obj_t * seat = lv_obj_get_child(seat_container, i);
        if(seat) {
            int * coord = (int *)lv_obj_get_user_data(seat);
            if(coord) {
                int row = coord[0];
                int col = coord[1];

                // 根据座位状态设置样式
                if(seats[row][col] == SEAT_AVAILABLE) {
                    lv_obj_set_style_bg_color(seat, lv_color_hex(0x00cc00), 0);
                    lv_obj_add_flag(seat, LV_OBJ_FLAG_CLICKABLE);
                } else if(seats[row][col] == SEAT_RESERVED) {
                    lv_obj_set_style_bg_color(seat, lv_color_hex(0xcc0000), 0);
                    lv_obj_clear_flag(seat, LV_OBJ_FLAG_CLICKABLE);
                } else if(seats[row][col] == SEAT_SELECTED) {
                    lv_obj_set_style_bg_color(seat, lv_color_hex(0xff9900), 0);
                    lv_obj_add_flag(seat, LV_OBJ_FLAG_CLICKABLE);
                }
            }
        }
    }
}

// 创建座位
static void create_seats(lv_obj_t * parent)
{
    for(int row = 0; row < SEAT_ROWS; row++) {
        for(int col = 0; col < SEAT_COLS; col++) {
            lv_obj_t * seat = lv_obj_create(parent);                        // 创建座位
            lv_obj_set_size(seat, 40, 40);                                  // 设置大小
            lv_obj_set_style_radius(seat, 6, 0);                            // 设置圆角
            lv_obj_set_style_border_width(seat, 1, 0);                      // 设置边框
            lv_obj_set_style_border_color(seat, lv_color_hex(0x999999), 0); // 设置边框颜色
            lv_obj_clear_flag(seat, LV_OBJ_FLAG_SCROLLABLE);                // 取消滚动

            // 设置网格位置
            lv_obj_set_grid_cell(seat, LV_GRID_ALIGN_CENTER, col, 1, LV_GRID_ALIGN_CENTER, row,
                                 1); // 设置网格位置 列，行

            // 存储座位坐标
            int * coord = lv_mem_alloc(2 * sizeof(int));
            coord[0]    = row;
            coord[1]    = col;
            lv_obj_set_user_data(seat, coord);

            // 座位号标签
            lv_obj_t * seat_label = lv_label_create(seat);
            lv_label_set_text_fmt(seat_label, "%c%d", 'A' + row, col + 1);
            lv_obj_center(seat_label);

            // 根据座位状态设置样式
            if(seats[row][col] == SEAT_AVAILABLE) {
                lv_obj_set_style_bg_color(seat, lv_color_hex(0x00cc00), 0);            // 创建一个绿色背景
                lv_obj_add_flag(seat, LV_OBJ_FLAG_CLICKABLE);                          // 添加点击功能
                lv_obj_add_event_cb(seat, seat_click_handler, LV_EVENT_CLICKED, NULL); // 添加点击事件处理函数
            } else if(seats[row][col] == SEAT_RESERVED) {
                lv_obj_set_style_bg_color(seat, lv_color_hex(0xcc0000), 0); // 创建一个红色背景
                lv_obj_clear_flag(seat, LV_OBJ_FLAG_CLICKABLE);             // 移除点击功能
            } else if(seats[row][col] == SEAT_SELECTED) {
                lv_obj_set_style_bg_color(seat, lv_color_hex(0xff9900), 0);            // 创建一个橙色背景
                lv_obj_add_flag(seat, LV_OBJ_FLAG_CLICKABLE);                          // 添加点击功能
                lv_obj_add_event_cb(seat, seat_click_handler, LV_EVENT_CLICKED, NULL); // 添加点击事件处理函数
            }
        }
    }
}

// 生成取票号: 0 + 电影编号 + 日期(YYYYMMDD) + 场次(小时分钟) + 座位号
static char * generate_ticket_number(int seat_idx)
{
    static char ticket_num[50];
    int row = seat_idx / SEAT_COLS;
    int col = seat_idx % SEAT_COLS;
    int hour, minute;

    // 解析时间中的小时和分钟
    if(sscanf(selected_time, "%d:%d", &hour, &minute) != 2) {
        hour   = 0;
        minute = 0;
    }

    // 从selected_date中提取日期信息 (格式为 "YYYY-MM-DD")
    int year, month, day;
    if(sscanf(selected_date, "%d-%d-%d", &year, &month, &day) == 3) {
        // 直接格式的日期
    } else {
        // 默认日期
        year  = 2023;
        month = 1;
        day   = 1;
    }

    // 生成取票号: 0 + 电影编号 + 日期(YYYYMMDD) + 场次(小时分钟) + 座位号
    snprintf(ticket_num, sizeof(ticket_num), "0%d%04d%02d%02d%02d%02d%c%d", current_movie.id, year, month, day, hour,
             minute, 'A' + row, col + 1);

    return ticket_num;
}

// 保存购票信息
static bool save_purchase_info(void)
{
    // 检查必要数据
    if(strlen(current_user.username) == 0 || strlen(current_user.phone) == 0 || !current_movie.name ||
       !selected_date[0] || !selected_time[0]) {
        LV_LOG_USER("Missing required purchase information: username=%s, phone=%s, movie=%s, date=%s, time=%s",
                    current_user.username, current_user.phone, current_movie.name ? current_movie.name : "NULL",
                    selected_date[0] ? selected_date : "NULL", selected_time[0] ? selected_time : "NULL");
        return false;
    }

    // 提取selected_date中的纯日期部分
    char pure_selected_date[20] = {0};
    if(strstr(selected_date, "(") != NULL) {
        // 格式如 "今天(2023-06-15)"，提取括号中的日期
        sscanf(selected_date, "%*[^(](%19[^)])", pure_selected_date);
    } else {
        // 直接使用selected_date
        strncpy(pure_selected_date, selected_date, sizeof(pure_selected_date) - 1);
    }

    // 打开buy.txt文件，不存在则创建，存在则追加
    FILE * file = fopen("buy.txt", "a+");
    if(!file) {
        LV_LOG_USER("Failed to open buy.txt");
        return false;
    }

    // 为每个座位单独写入一行记录
    bool success = true;
    if(selected_count > 0) {
        for(int i = 0; i < selected_count; i++) {
            int row = selected_seats[i] / SEAT_COLS;
            int col = selected_seats[i] % SEAT_COLS;

            // 座位号
            char seat[10];
            snprintf(seat, sizeof(seat), "%c%d", 'A' + row, col + 1);

            // 取票号
            char ticket_num[50];
            strcpy(ticket_num, generate_ticket_number(selected_seats[i]));

            // 写入购票信息：
            // 用户名,号码,电影名,日期,场次,座位号,取票号,取票情况(0表示未取票),取票时间(0表示未取票)
            int result = fprintf(file, "%s,%s,%s,%s,%s,%s,%s,0,0\n", current_user.username, current_user.phone,
                                 current_movie.name, pure_selected_date, selected_time, seat, ticket_num);

            if(result <= 0) {
                success = false;
                LV_LOG_USER("Failed to write purchase info to buy.txt");
                break;
            }

            LV_LOG_USER("Successfully wrote purchase info to buy.txt: %s,%s,%s,%s,%s,%s,%s,0,0", current_user.username,
                        current_user.phone, current_movie.name, pure_selected_date, selected_time, seat, ticket_num);
        }
    } else {
        LV_LOG_USER("No seats selected");
        success = false;
    }

    fclose(file);

    if(success) {
        // 更新场次剩余票数
        update_show_time_remaining();
        LV_LOG_USER("Purchase info saved successfully");
        return true;
    }

    LV_LOG_USER("Failed to save purchase info");
    return false;
}
// 确认购票回调
static void confirm_purchase(lv_event_t * e)
{
    if(lv_event_get_code(e) == LV_EVENT_CLICKED) {
        if(selected_count == 0) {
            lv_obj_t * msg = lv_msgbox_create(NULL, "提示", "请至少选择一个座位", NULL, false);
            lv_obj_center(msg);
            lv_timer_t * timer = lv_timer_create(close_msgbox_simple_cb, 2000, msg);
            lv_timer_set_repeat_count(timer, 1);
            return;
        }

        // 检查必要的变量是否有效
        if(!current_movie.name || !selected_date[0] || !selected_time[0] || !selected_hall[0]) {
            lv_obj_t * msg = lv_msgbox_create(NULL, "错误", "购票信息不完整", NULL, false);
            lv_obj_center(msg);
            lv_timer_t * timer = lv_timer_create(close_msgbox_simple_cb, 2000, msg);
            lv_timer_set_repeat_count(timer, 1);
            return;
        }

        // 构造订单信息
        char seat_text[200] = {0};
        if(selected_count > 0) {
            for(int i = 0; i < selected_count; i++) {
                // 确保索引有效
                if(i >= MAX_SELECTED_SEATS) break;

                int row = selected_seats[i] / SEAT_COLS;
                int col = selected_seats[i] % SEAT_COLS;

                // 确保行列索引有效
                if(row >= 0 && row < SEAT_ROWS && col >= 0 && col < SEAT_COLS) {
                    char temp[10];
                    snprintf(temp, sizeof(temp), "%c%d,", 'A' + row, col + 1);
                    strcat(seat_text, temp);
                }
            }
            if(strlen(seat_text) > 0) {
                seat_text[strlen(seat_text) - 1] = '\0'; // 移除最后一个逗号
            }
        } else {
            strcpy(seat_text, "无");
        }

        char info[500];
        snprintf(info, sizeof(info),
                 "电影: %s\n日期: %s\n时间: %s\n影厅: %s\n座位: %s\n\n单价: %d元\n总价: %d元\n\n确认购买?",
                 current_movie.name ? current_movie.name : "未知电影", selected_date[0] ? selected_date : "未知日期",
                 selected_time[0] ? selected_time : "未知时间", selected_hall[0] ? selected_hall : "未知影厅",
                 seat_text, current_movie.price, selected_count * current_movie.price);

        // 创建确认对话框
        static const char * btns[] = {"取消", "确认", ""}; // 使用static关键字确保数组在函数返回后仍然有效
        lv_obj_t * confirm_msg     = lv_msgbox_create(NULL, "确认订单", info, btns, false);
        lv_obj_center(confirm_msg);
        lv_obj_set_style_max_width(confirm_msg, 500, 0);

        // 对话框事件处理
        lv_obj_add_event_cb(confirm_msg, msgbox_event_handler, LV_EVENT_VALUE_CHANGED, NULL);
    }
}
// 安全删除对象的辅助函数，确保删除所有相关对象包括遮罩层
static void safe_delete_msgbox(lv_obj_t * msgbox) 
{
    if (!msgbox) return;
    
    // 获取消息框的父对象（通常是屏幕或遮罩层的父对象）
    lv_obj_t * parent = lv_obj_get_parent(msgbox);
    
    // 删除消息框
    lv_obj_del(msgbox);
    
    // 检查父对象是否为遮罩层（通常是一个透明的覆盖整个屏幕的对象）
    if (parent && lv_obj_get_child_cnt(parent) == 0) {
        // 如果父对象没有其他子对象，可能是遮罩层，也一并删除
        // 但要确保不是主屏幕
        if (parent != lv_scr_act() && parent != ticket_screen) {
            lv_obj_del(parent);
        }
    }
}

// 简单关闭消息框的定时器回调（用于提示信息等不需要页面跳转的场景）
static void close_msgbox_simple_cb(lv_timer_t * timer)
{
    lv_obj_t * msgbox = (lv_obj_t *)timer->user_data;
    if(msgbox) {
        safe_delete_msgbox(msgbox);
    }
    
    // 删除定时器本身以避免内存泄漏
    lv_timer_del(timer);
}
// 消息框事件处理函数
static void msgbox_event_handler(lv_event_t * e)
{
    lv_obj_t * msgbox  = lv_event_get_current_target(e);
    uint16_t button_id = lv_msgbox_get_active_btn(msgbox);
    bool delete_msgbox = true;  // 默认需要删除消息框

    if(button_id == 1) { // 确认按钮
        if(save_purchase_info()) {
            // 为每个座位生成订单信息
            char order_info[1000] = "订单详情:\n";
            char temp[200];

            if(selected_count > 0) {
                for(int i = 0; i < selected_count; i++) {
                    int row = selected_seats[i] / SEAT_COLS;
                    int col = selected_seats[i] % SEAT_COLS;

                    snprintf(temp, sizeof(temp),
                             "用户: %s\n电话: %s\n电影: %s\n日期: %s\n时间: %s\n座位: %c%d\n取票号: %s\n\n",
                             current_user.username, current_user.phone, current_movie.name, selected_date,
                             selected_time, 'A' + row, col + 1, generate_ticket_number(selected_seats[i]));
                    strcat(order_info, temp);
                }
            } else {
                strcat(order_info, "无座位信息\n");
            }

            // 创建支付成功弹窗
            lv_obj_t * payment_msgbox = lv_msgbox_create(NULL, "支付成功", order_info, NULL, false);
            lv_obj_center(payment_msgbox);
            lv_obj_set_style_max_width(payment_msgbox, 500, 0);

            // 5秒后自动关闭并刷新座位页面
            lv_timer_t * timer = lv_timer_create(close_msgbox_simple_cb, 5000, payment_msgbox);
            lv_timer_set_repeat_count(timer, 1);
            delete_msgbox = false;  // 支付成功消息框有自己的定时器处理删除

            // 重置选择状态
            reset_seat_selection();
            
            // 更新座位显示状态
            if (seat_selection_page && !lv_obj_has_flag(seat_selection_page, LV_OBJ_FLAG_HIDDEN)) {
                // 更新座位状态
                update_seat_status_from_file();

                // 更新座位显示
                lv_obj_t * seat_container = lv_obj_get_child(seat_selection_page, -1); // 获取座位容器
                if(seat_container) {
                    seat_container = lv_obj_get_child(seat_container, -1); // 获取座位网格容器
                    if(seat_container) {
                        // 更新座位显示状态
                        update_seat_display(seat_container);
                    }
                }
            }
        } else {
            lv_obj_t * error_msgbox = lv_msgbox_create(NULL, "错误", "保存购票信息失败", NULL, false);
            lv_obj_center(error_msgbox);
            lv_timer_t * timer = lv_timer_create(close_msgbox_simple_cb, 3000, error_msgbox);
            lv_timer_set_repeat_count(timer, 1);
            delete_msgbox = false;  // 错误消息框有自己的定时器处理删除
        }
    } else if(button_id == 0) { // 取消按钮
        // 不需要额外操作，因为已经在座位选择页面
        // 消息框会在函数末尾被删除
    }

    // 确保消息框被正确删除
    if(delete_msgbox && msgbox) {
        safe_delete_msgbox(msgbox);
    }
}
